﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;

namespace FileExplorer
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = this;
            LoadFolders(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile));
        }

        public List<FolderItem> Folders { get; set; } = new List<FolderItem>();
        public List<FileInfo> Files { get; set; } = new List<FileInfo>();

        private void LoadFolders(string path)
        {
            Folders.Clear();
            try
            {
                foreach (var directory in Directory.GetDirectories(path))
                {
                    var folderItem = new FolderItem { Name = Path.GetFileName(directory) };
                    Folders.Add(folderItem);
                    LoadSubFolders(directory, folderItem);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error loading folders: {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void LoadSubFolders(string path, FolderItem parentFolder)
        {
            foreach (var directory in Directory.GetDirectories(path))
            {
                var folderItem = new FolderItem { Name = Path.GetFileName(directory) };
                parentFolder.SubFolders.Add(folderItem);
                LoadSubFolders(directory, folderItem);
            }
        }

        private void ListViewItem_MouseDoubleClick(object sender, RoutedEventArgs e)
        {
            var selectedFile = (FileInfo)listViewFiles.SelectedItem;
            if (selectedFile != null && selectedFile.Extension.ToLower() == ".txt")
            {
                System.Diagnostics.Process.Start(selectedFile.FullName);
            }
        }
    }

    public class FolderItem
    {
        public string Name { get; set; }
        public List<FolderItem> SubFolders { get; set; } = new List<FolderItem>();
    }
}
